{% extends "base.html" %}

{% block title %}管理员仪表盘 - IT课程数据分析系统{% endblock %}

{% block extra_css %}
<style>
    .stats-grid {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
        gap: 1.5rem;
        margin-bottom: 2rem;
    }
    
    .stat-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 8px;
        padding: 1.5rem;
    }
    
    .stat-card:nth-child(2) {
        background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    }
    
    .stat-card:nth-child(3) {
        background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
    }
    
    .stat-card:nth-child(4) {
        background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
    }
    
    .stat-card h3 {
        font-size: 0.9rem;
        opacity: 0.9;
        margin-bottom: 0.5rem;
    }
    
    .stat-card .value {
        font-size: 2.5rem;
        font-weight: 700;
    }
    
    .chart-container {
        height: 400px;
        width: 100%;
    }
    /* 让图表铺满卡片可视区域 */
    .chart-card {
        height: 480px;
        display: flex;
        flex-direction: column;
    }
    .chart-card .chart-container {
        height: auto;
        flex: 1;
    }
    
    .quick-actions {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 1rem;
        margin-bottom: 2rem;
    }
    
    .action-btn {
        padding: 1rem;
        background: white;
        border: 2px solid #e0e0e0;
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.3s;
        text-align: center;
    }
    
    .action-btn:hover {
        border-color: #3498db;
        box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    }
    
    .action-btn .icon {
        font-size: 2rem;
        margin-bottom: 0.5rem;
    }
</style>
{% endblock %}

{% block content %}
<h2 style="margin-bottom:1.5rem;">管理员仪表盘</h2>

<div id="loading" class="loading">
    <div class="spinner"></div>
    <p>加载中...</p>
</div>

<div id="dashboard-content" style="display:none;">
    <!-- 统计卡片 -->
    <div class="stats-grid">
        <div class="stat-card">
            <h3>总用户数</h3>
            <div class="value" id="total-users">-</div>
        </div>
        <div class="stat-card">
            <h3>学生数量</h3>
            <div class="value" id="total-students">-</div>
        </div>
        <div class="stat-card">
            <h3>课程数量</h3>
            <div class="value" id="total-courses">-</div>
        </div>
        <div class="stat-card">
            <h3>成绩记录</h3>
            <div class="value" id="total-grades">-</div>
        </div>
    </div>
    
    <!-- 快速操作 -->
    <div class="card">
        <div class="card-title">快速操作</div>
        <div class="quick-actions">
            <div class="action-btn" onclick="window.location.href='/admin/import'">
                <div class="icon">📤</div>
                <div>数据导入</div>
            </div>
            <div class="action-btn" onclick="window.location.href='/admin/users'">
                <div class="icon">👥</div>
                <div>用户管理</div>
            </div>
            <div class="action-btn" onclick="window.location.href='/admin/courses'">
                <div class="icon">📚</div>
                <div>课程管理</div>
            </div>
            <div class="action-btn" onclick="window.location.href='/admin/settings'">
                <div class="icon">⚙️</div>
                <div>系统设置</div>
            </div>
        </div>
    </div>
    
    <!-- 课程热度排行 -->
    <div class="card chart-card">
        <div class="card-title">课程热度排行 Top 10</div>
        <div id="popularity-chart" class="chart-container"></div>
    </div>
    
    <!-- 系统活跃度 -->
    <div class="card chart-card">
        <div class="card-title">系统活跃度（最近7天）</div>
        <div id="activity-chart" class="chart-container"></div>
    </div>
    
    <!-- 操作类型分布 -->
    <div class="card chart-card">
        <div class="card-title">操作类型分布</div>
        <div id="action-chart" class="chart-container"></div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 动态加载ECharts，提供多个CDN备用方案
(function() {
    const cdnUrls = [
        'https://cdn.bootcdn.net/ajax/libs/echarts/5.4.0/echarts.min.js',
        'https://cdn.staticfile.org/echarts/5.4.0/echarts.min.js',
        'https://lib.baomitu.com/echarts/5.4.0/echarts.min.js'
    ];
    
    function loadScript(url, index = 0) {
        return new Promise((resolve, reject) => {
            const script = document.createElement('script');
            script.src = url;
            script.onload = () => resolve(true);
            script.onerror = () => {
                console.warn(`CDN ${index + 1} 加载失败: ${url}`);
                if (index < cdnUrls.length - 1) {
                    loadScript(cdnUrls[index + 1], index + 1).then(resolve).catch(reject);
                } else {
                    reject(new Error('所有ECharts CDN加载失败'));
                }
            };
            document.head.appendChild(script);
        });
    }
    
    // 尝试加载ECharts
    loadScript(cdnUrls[0]).catch(err => {
        console.error('ECharts加载失败，将使用备用显示方案:', err);
    });
})();

// 等待ECharts加载完成
function waitForEcharts(timeout = 10000) {
    return new Promise((resolve, reject) => {
        const startTime = Date.now();
        
        function check() {
            if (typeof echarts !== 'undefined') {
                resolve();
            } else if (Date.now() - startTime > timeout) {
                reject(new Error('ECharts加载超时'));
            } else {
                setTimeout(check, 100);
            }
        }
        
        check();
    });
}
</script>
<script>
    async function loadDashboard() {
        try {
            const userInfo = JSON.parse(localStorage.getItem('user_info') || '{}');
            
            if (userInfo.role !== 'admin') {
                showAlert('权限不足', 'error');
                setTimeout(() => window.location.href = '/', 2000);
                return;
            }
            
            // 加载统计数据（模拟）
            loadStats();
            
            // 先显示内容区域，再初始化图表（避免ECharts在display:none时计算为0宽度）
            document.getElementById('loading').style.display = 'none';
            document.getElementById('dashboard-content').style.display = 'block';

             // 加载课程热度
             await loadCoursePopularity();
             
             // 加载系统活跃度
             await loadSystemActivity();
             
             // 加载操作分布
             await loadActionDistribution();
             
         } catch (error) {
             showAlert('加载失败: ' + error.message, 'error');
         }
     }
    
    function loadStats() {
        // 这里应该调用API获取真实统计数据
        // 暂时使用演示数据
        document.getElementById('total-users').textContent = '1031';
        document.getElementById('total-students').textContent = '1000';
        document.getElementById('total-courses').textContent = '25';
        document.getElementById('total-grades').textContent = '20000+';
    }
    
    async function loadCoursePopularity() {
        try {
            const data = await apiRequest('/analytics/courses/popularity?limit=10');
            
            if (data.success) {
                const courses = data.data;
                const chartElement = document.getElementById('popularity-chart');
                
                // 检查是否有数据
                if (!courses || courses.length === 0) {
                    chartElement.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#7f8c8d;"><p>暂无选课数据，请先导入学生选课信息</p></div>';
                    return;
                }
                
                // 等待ECharts加载（最多等待10秒）
                try {
                    await waitForEcharts();
                } catch (error) {
                    chartElement.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#e74c3c;"><p>图表库加载失败，请刷新页面重试</p></div>';
                    return;
                }
                
                const chart = echarts.init(chartElement);
                chart.setOption({
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        },
                        formatter: function(params) {
                            const item = params[0];
                            return `<strong style="font-size:14px;">${item.name}</strong><br/>选课人数: <strong style="color:#3498db;font-size:15px;">${item.value}</strong>`;
                        }
                    },
                    grid: {
                        left: '18%',
                        right: '6%',
                        top: '5%',
                        bottom: '12%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'value',
                        name: '选课人数',
                        nameLocation: 'middle',
                        nameGap: 35,
                        nameTextStyle: {
                            fontSize: 14,
                            fontWeight: 'bold',
                            color: '#2c3e50'
                        },
                        axisLine: {
                            lineStyle: {
                                color: '#d0d0d0'
                            }
                        },
                        splitLine: {
                            lineStyle: {
                                color: '#f0f0f0'
                            }
                        }
                    },
                    yAxis: {
                        type: 'category',
                        data: courses.map(c => c.course_name).reverse(),
                        axisLabel: {
                            interval: 0,
                            fontSize: 13,
                            color: '#2c3e50',
                            fontWeight: '500',
                            margin: 6,
                            formatter: function(value) {
                                return value;
                            }
                        },
                        axisLine: {
                            lineStyle: {
                                color: '#d0d0d0'
                            }
                        },
                        axisTick: {
                            show: false
                        }
                    },
                    series: [{
                        data: courses.map(c => c.enrollment_count).reverse(),
                        type: 'bar',
                        barWidth: '60%',
                        itemStyle: {
                            color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                                { offset: 0, color: '#667eea' },
                                { offset: 1, color: '#764ba2' }
                            ]),
                            borderRadius: [0, 8, 8, 0],
                            shadowColor: 'rgba(102, 126, 234, 0.4)',
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowOffsetY: 2
                        },
                        label: {
                            show: true,
                            position: 'right',
                            fontSize: 13,
                            fontWeight: 'bold',
                            color: '#2c3e50',
                            formatter: '{c}'
                        }
                    }]
                });

                // 自适应容器尺寸变化
                window.addEventListener('resize', () => chart.resize());
                // 确保首次渲染后按可见尺寸布局
                setTimeout(() => chart.resize(), 0);
            }
        } catch (error) {
            console.error('加载课程热度失败:', error);
            document.getElementById('popularity-chart').innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#e74c3c;"><p>加载失败: ' + error.message + '</p></div>';
        }
    }
    
     async function loadSystemActivity() {
         try {
             const data = await apiRequest('/analytics/system/activity?days=7');
             
             if (data.success) {
                 const activityData = data.data;
                 const dailyData = activityData.daily_activity;
                 
                 if (!dailyData || dailyData.length === 0) {
                     document.getElementById('activity-chart').innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#7f8c8d;"><p>暂无活跃度数据</p></div>';
                     return;
                 }
                 
                 // 等待ECharts加载
                 try {
                     await waitForEcharts();
                 } catch (error) {
                     return;
                 }
                 
                 const dates = dailyData.map(d => d.date);
                 const activeUsers = dailyData.map(d => d.active_users);
                 const totalActions = dailyData.map(d => d.total_actions);
                 
                 const chart = echarts.init(document.getElementById('activity-chart'));
                 chart.setOption({
                     title: {
                         text: `总操作数: ${activityData.summary.total_actions} | 活跃用户: ${activityData.summary.unique_users}`,
                         textStyle: {
                             fontSize: 14,
                             fontWeight: 'normal',
                             color: '#7f8c8d'
                         }
                     },
                     tooltip: {
                         trigger: 'axis',
                         axisPointer: {
                             type: 'cross'
                         }
                     },
                     legend: {
                         data: ['活跃用户数', '操作次数'],
                         bottom: 0
                     },
                     grid: {
                         left: '3%',
                         right: '4%',
                         bottom: '12%',
                         top: '15%',
                         containLabel: true
                     },
                     xAxis: {
                         type: 'category',
                         data: dates,
                         axisLabel: {
                             rotate: 45
                         }
                     },
                     yAxis: [
                         {
                             type: 'value',
                             name: '活跃用户数',
                             position: 'left',
                             axisLabel: {
                                 formatter: '{value}'
                             }
                         },
                         {
                             type: 'value',
                             name: '操作次数',
                             position: 'right',
                             axisLabel: {
                                 formatter: '{value}'
                             }
                         }
                     ],
                     series: [
                         {
                             name: '活跃用户数',
                             type: 'line',
                             data: activeUsers,
                             smooth: true,
                             itemStyle: {
                                 color: '#3498db'
                             },
                             areaStyle: {
                                 opacity: 0.3
                             }
                         },
                         {
                             name: '操作次数',
                             type: 'line',
                             yAxisIndex: 1,
                             data: totalActions,
                             smooth: true,
                             itemStyle: {
                                 color: '#e74c3c'
                             }
                         }
                     ]
                 });
                 
                 window.addEventListener('resize', () => chart.resize());
                 setTimeout(() => chart.resize(), 0);
             }
         } catch (error) {
             console.error('加载系统活跃度失败:', error);
             document.getElementById('activity-chart').innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#e74c3c;"><p>加载失败: ' + error.message + '</p></div>';
         }
     }
     
     async function loadActionDistribution() {
         try {
             const data = await apiRequest('/analytics/system/activity?days=7');
             
             if (data.success) {
                 const actionStats = data.data.action_stats;
                 
                 if (!actionStats || Object.keys(actionStats).length === 0) {
                     document.getElementById('action-chart').innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#7f8c8d;"><p>暂无操作数据</p></div>';
                     return;
                 }
                 
                 // 等待ECharts加载
                 try {
                     await waitForEcharts();
                 } catch (error) {
                     return;
                 }
                 
                 // 转换为图表数据格式
                 const chartData = Object.entries(actionStats).map(([name, value]) => ({
                     name: name || '未知操作',
                     value: value
                 }));
                 
                 const chart = echarts.init(document.getElementById('action-chart'));
                 chart.setOption({
                     tooltip: {
                         trigger: 'item',
                         formatter: '{b}: {c} ({d}%)'
                     },
                     legend: {
                         orient: 'vertical',
                         left: 'right',
                         top: 'center',
                         formatter: function(name) {
                             return name.length > 15 ? name.substring(0, 15) + '...' : name;
                         }
                     },
                     series: [
                         {
                             name: '操作类型',
                             type: 'pie',
                             radius: ['40%', '70%'],
                             avoidLabelOverlap: true,
                             itemStyle: {
                                 borderRadius: 10,
                                 borderColor: '#fff',
                                 borderWidth: 2
                             },
                             label: {
                                 show: true,
                                 formatter: '{b}: {d}%'
                             },
                             emphasis: {
                                 label: {
                                     show: true,
                                     fontSize: 16,
                                     fontWeight: 'bold'
                                 }
                             },
                             data: chartData
                         }
                     ]
                 });
                 
                 window.addEventListener('resize', () => chart.resize());
                 setTimeout(() => chart.resize(), 0);
             }
         } catch (error) {
             console.error('加载操作分布失败:', error);
             document.getElementById('action-chart').innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#e74c3c;"><p>加载失败: ' + error.message + '</p></div>';
         }
     }
     
     // 页面加载时执行
     window.addEventListener('DOMContentLoaded', loadDashboard);
 </script>
 {% endblock %}

